package com.zzyl.service.impl;

import com.zzyl.service.WorkFlowService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class WorkFlowServiceImpl implements WorkFlowService {
    @Resource
    RepositoryService repositoryService;

    @Resource
    RuntimeService runtimeService;

    @Resource
    TaskService taskService;


    @Resource
    HistoryService historyService;

    @Override
    public void deploy(String bpmnResource, String imgResource, String bpmnNmae) {
        repositoryService.createDeployment()
                .addClasspathResource(bpmnResource)
                .addClasspathResource(imgResource)
                .name(bpmnNmae)
                .deploy();
    }

    @Override
    public void deleteDeployment(String deploymentId) {
        repositoryService.deleteDeployment(deploymentId,true);
    }

    @Override
    public void startProcess(String precessKey, String businessKey, Map<String, Object> variables) {
        runtimeService.startProcessInstanceByKey(precessKey,businessKey,variables);
    }

    @Override
    public List<Task> queryRuntimeProcess(String assignee) {
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).list();
        return list;
    }

    @Override
    public void completeTask(String assignee,Map<String, Object> variables) {
        List<Task> tasks = queryRuntimeProcess(assignee);
        for (Task task : tasks) {
            taskService.complete(task.getId(),variables,true);
        }
    }

    @Override
    public void completeTaskByTaskId(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId,variables);
    }


    @Override
    public void rejectTask(String taskId, String reason) {
        runtimeService.deleteProcessInstance(taskId,reason);
    }

    @Override
    public List<Task> queryTaskByPage(Integer pageNum, Integer pageSize,String assgineeId) {
        return taskService.createTaskQuery().taskAssignee(assgineeId)
                .listPage((pageNum-1)*pageSize, pageSize);
    }

    @Override
    public List<HistoricTaskInstance> queryHistoryTask(Integer pageNum, Integer pageSize,String assgineeId) {
        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(assgineeId)
                .finished()
                .listPage((pageNum - 1) * pageSize, pageSize);
        return historicTaskInstances;
    }


}

